#include "downloader.h"
#include "trace.h"

using namespace Downloader;
using namespace Downloader::Trace;

// downloader 构造
downloader::downloader():version(DOWNLOADER_VERSION)
{
	TRACE(DTRACE_LVL_INFO, "%s\n", __func__);
}

// 获取版本信息
string downloader::get_version(void)
{
	TRACE(DTRACE_LVL_INFO, "Current Version: %s\n", version.data());

	return version;
}

int downloader::set_info(struct downloader_para *para)
{
	if (!para) {
		TRACE(DTRACE_LVL_ERROR, "set downloader info failed, para is NULL\n");
		return -1;
	}

	d_para = new downloader_para; // 注意失败处理

	d_para = para;

	return 0;
}

void downloader::main_thread_entry(downloader *dw)
{
	TRACE(DTRACE_LVL_INFO, "Start main thread.\n");

	while (1) {
		TRACE(DTRACE_LVL_INFO, "%s\n", __func__);
		fflush(stdout);
		sleep(1);
	}
}

// downloader 析构
downloader::~downloader()
{
	TRACE(DTRACE_LVL_INFO, "%s\n", __func__);
}

int downloader_start(struct downloader_para *para)
{
	TRACE(DTRACE_LVL_INFO, "Start a downloader task.\n");

	downloader *dw = new downloader;

	dw->get_version();
	dw->set_info(para);

	thread main_thread(bind(&downloader::main_thread_entry, dw, dw));

	main_thread.detach();

	return 0;
}

#ifdef DOWNLOADER_WHOLE

void downloader_whole_hook(const char *file, int result, void *arg)
{
	TRACE(DTRACE_LVL_INFO, "%s\n", __func__);
	TRACE(DTRACE_LVL_INFO, "file %s, result %d, arg %p\n", file, result , arg);
}

int main(int argc, const char *argv[])
{
	struct downloader_para para;

	para.url = "ftp://ceshi:ceshi@192.168.3.201:2714/hello.ini";
	para.save_path = "download";
	para.thread_cnt = 2;
	para.usr_arg = nullptr;
	para.hook = downloader_whole_hook;
	downloader_start(&para);

	while (1)
	{
		TRACE(DTRACE_LVL_INFO, "%s\n", __func__);
		fflush(stdout);
		sleep(1);
	}

    return 0;
}

#endif	// #ifdef DOWNLOADER_WHOLE
